<script setup>
import { computed, ref, nextTick, reactive } from "vue";
import { BaiduMap, BmPolygon, useMap } from "vue-baidu-map-3x";
import {
  getPoint,
  getLine,
  getAllStatePoint,
  changeState,
  addPoint,
  getFileName,
  getFile
} from "../api/point";
import { ElMessage } from "element-plus";
/* 变量------------------------------------ */
const center = ref({ lng: 119.536067, lat: 39.915018 });
const BMapRef = ref(null);
const mapRef = ref(null);
const zoom = ref(16);
let mapData = ref([]);
let mapLine = ref([]);
let AllPoint = ref([]);
//点位管理对话框是否打开
const pointManagement = ref(false);
const addDialog = ref(false);
const logDialog = ref(false)
// 引用表单
const addFormRef = ref();
const addForm = reactive({
  position: "",
  name: "",
});
const fileNames = ref([]);
/* 方法-------------------------------------- */
const downloadFile = (file) =>{
    getFile(file);
}
const getAllFileName = async () =>{
  fileNames.value = [];
  const data = await getFileName();
  for(var a=0;a<data.length;a++){
    fileNames.value.push({
      name:data[a]
    })
  }
  logDialog.value = true
}
const openPointManagement = async () => {
  pointManagement.value = true;
  const data = await getAllStatePoint();
  AllPoint.value = data.map((point) => ({
    id: point.id,
    lng: point.lng,
    lat: point.lat,
    name: point.name,
    state: point.state,
  }));
};
const totalDistance = computed(() => {
  return mapLine.value.reduce((total, line) => total + line.distance, 0);
});
async function getAllLine() {
  const data = await getLine();
  mapLine.value = data.map((line) => ({
    fromName: line.fromName,
    fromLat: line.fromLat,
    fromLng: line.fromLng,
    toName: line.toName,
    toLat: line.toLat,
    toLng: line.toLng,
    distance: line.distance,
  }));
}
async function getAllPoint() {
  const data = await getPoint();
  mapData.value = data.map((point) => ({
    id: point.id,
    lng: point.lng,
    lat: point.lat,
    name: point.name,
  }));
}
const handler = async ({ BMap, map }) => {
  BMapRef.value = BMap;
  mapRef.value = map;
  // 清除杂物
  await map.clearOverlays();
  // 获取点和线的数据
  await getAllPoint();
  await getAllLine();
  // 设置地图中心和缩放
  let point = new BMap.Point(center.value.lng, center.value.lat);
  map.centerAndZoom(point, zoom.value);
  await new Promise((resolve) => setTimeout(resolve, 1000));
  await drawLines(map);
};

// 绘制所有线的函数
const drawLines = async (map) => {
  for (const line of mapLine.value) {
    const pointA = new BMap.Point(line.fromLng, line.fromLat);
    const pointB = new BMap.Point(line.toLng, line.toLat);

    const polyline = new BMap.Polyline([pointA, pointB], {
      strokeColor: "blue",
      strokeWeight: 6,
      strokeOpacity: 0.4,
    });
    map.addOverlay(polyline);
    await new Promise((resolve) => setTimeout(resolve, 1700));
  }
};
const restartMap = async () => {
  location.reload();
};


// 验证坐标格式
const validatePosition = (rule, value, callback) => {
  const regex = /^-?\d+(\.\d+)?,\s*-?\d+(\.\d+)?$/;
  if (!addForm.position) {
    positionWhetherRule.value = false;
    callback(new Error("坐标必填"));
  } else if (!regex.test(addForm.position)) {
    positionWhetherRule.value = false;
    callback(
      new Error('坐标格式不正确，应该为 "经度,纬度", 如 119.524515,39.917183')
    );
  } else {
    positionWhetherRule.value = true;
    callback();
  }
};
const validateName = (rule, value, callback) => {
  const regex = /^-?\d+(\.\d+)?,\s*-?\d+(\.\d+)?$/;
  if (!addForm.name) {
    nameWhetherRule.value = false;
    callback(new Error("名字必填"));
  } else if (addForm.name == "") {
    nameWhetherRule.value = false;
    callback(new Error("名字必填"));
  } else {
    nameWhetherRule.value = true;
    callback();
  }
};
const nameWhetherRule = ref(false);
const positionWhetherRule = ref(false);
// 验证规则
const rules = reactive({
  position: [
    {
      validator: validatePosition,
      trigger: "blur",
    },
  ],
  name: [
    {
      validator: validateName,
      trigger: "blur",
    },
  ],
});
// 提交表单
const submitForm = async (formEl) => {
  if (nameWhetherRule.value == true && positionWhetherRule.value == true) {
    const [longitude, latitude] = addForm.position.split(",");
    const flag = await addPoint(latitude, longitude, addForm.name);
    if (flag == 1) {
      resetForm();
      ElMessage({
        message: "添加成功",
        type: "success",
        plain: true,
      });
    }
  } else {
    ElMessage({
      message: "添加失败",
      type: "error",
      plain: true,
    });
  }
};
const resetForm = () => {
  (addForm.name = ""), (addForm.position = "");
};
</script>
<template>
  <div class="main">
    <!-- 左边百度地图------------------------------------------------- -->
    <div class="left">
      <baidu-map
        class="bm-view"
        :center="center"
        :zoom="zoom"
        :scroll-wheel-zoom="true"
        @ready="handler"
      >
        <!-- 城市列表 -->
        <bm-city-list anchor="BMAP_ANCHOR_TOP_LEFT" />
        <!-- 缩放工具 -->
        <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
        <!-- 视图切换 -->
        <bm-map-type
          :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']"
          anchor="BMAP_ANCHOR_TOP_LEFT"
        ></bm-map-type>
        <!-- 标注 -->
        <bm-marker
          v-for="(item, index) in mapData"
          :key="index"
          :position="{ lng: item.lng, lat: item.lat }"
          :clicking="false"
          animation="BMAP_ANIMATION_BOUNCE"
        >
          <bm-label
            :content="item.name"
            :label-style="{ color: 'red', fontSize: '10px' }"
            :offset="{ width: -25, height: 20 }"
          />
        </bm-marker>
      </baidu-map>
    </div>
    <!-- 右边数据控制台------------------------------------------------- -->
    <div class="right">
      <div
        style="
          display: flex;
          flex-direction: column;
          align-items: center;
          padding-top: 20px;
        "
      >
        <div class="scroll-text" style="height: 300px">
          <el-table :data="mapData" style="width: 100%; height: 100%">
            <el-table-column prop="name" label="点位名称" width="150" />
            <el-table-column prop="lng" label="经度" width="110" />
            <el-table-column prop="lat" label="纬度" width="100" />
          </el-table>
        </div>
        <div class="scroll-text" style="height: 300px">
          <el-table :data="mapLine" style="width: 100%; height: 100%">
            <el-table-column prop="fromName" label="点位1名称" width="120" />
            <el-table-column prop="toName" label="点位2名称" width="120" />
            <el-table-column
              prop="distance"
              label="距离(单位：米)"
              width="120"
            />
          </el-table>
        </div>
      </div>
      <div
        style="
          margin-top: 18px;
          overflow: auto;
          display: flex;
          margin-left: 80px;
        "
      >
        <el-button @click="openPointManagement()">点位管理</el-button>
        <el-button style="margin-left: 40px" @click="getAllFileName()">查看日志</el-button>
        <el-button style="margin-left: 40px" @click="restartMap"
          >Restart</el-button
        >
      </div>
      <div style="margin-top: 10px">
        <el-text class="mx-1" style="margin-left: 165px"
          >当前管道总长度: {{ totalDistance }} 米</el-text
        >
      </div>
    </div>

    <!-- 对话框部分------------------------------------------------- -->
    <!-- 点位管理对话框 -->
    <el-dialog v-model="pointManagement" title="点位管理" width="620" draggable>
      <el-dialog
        v-model="addDialog"
        width="500"
        title="新增点位"
        append-to-body
        draggable
      >
        <div style="margin-bottom: 15px">
          <span>请在这儿那坐标-></span>
          <a href="https://api.map.baidu.com/lbsapi/getpoint/" target="_blank"
            >百度地图坐标拾取器</a
          >
        </div>
        <el-form
          ref="addFormRef"
          style="max-width: 600px"
          :model="ruleForm"
          status-icon
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
        >
          <el-form-item label="坐标" prop="position">
            <el-input v-model="addForm.position" autocomplete="off" />
          </el-form-item>
          <el-form-item label="名字" prop="name">
            <el-input v-model="addForm.name" autocomplete="off" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(addFormRef)">
              提交
            </el-button>
            <el-button @click="resetForm()">重置</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <el-table :data="AllPoint" style="width: 100%" max-height="460">
        <el-table-column prop="id" label="id" width="50" />
        <el-table-column prop="lng" label="经度" width="110" />
        <el-table-column prop="lat" label="纬度" width="100" />
        <el-table-column prop="name" label="建筑名" width="120" />
        <el-table-column fixed="right" label="操作" min-width="200">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click.prevent="deleteRow(scope.$index)"
            >
              删除
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click.prevent="deleteRow(scope.$index)"
            >
              修改
            </el-button>
            <el-switch
              v-model="AllPoint[scope.$index].state"
              inline-prompt
              :active-value="1"
              :inactive-value="0"
              active-text="已选"
              inactive-text="未选"
              style="margin-left: 5px"
              @change="changeState(AllPoint[scope.$index].id, $event)"
            />
          </template>
        </el-table-column>
      </el-table>
      <el-button class="mt-4" style="width: 100%" @click="addDialog = true">
        新增
      </el-button>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="pointManagement = false">取消</el-button>
          <el-button type="primary" @click="pointManagement = false">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <el-dialog v-model="logDialog" title="运行日志(日志只存储3分钟，请尽快下载)" width="500" draggable>
    <el-table :data="fileNames">
      <el-table-column property="name" label="日志名(日期_时间 算法)" width="300" />
      <el-table-column fixed="right" label="操作" min-width="80">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click.prevent="downloadFile(fileNames[scope.$index].name)"
            >
              下载
            </el-button>
          </template>
        </el-table-column>
    </el-table>
  </el-dialog>

</template>

<style>
.main {
  display: flex;
  width: 100vw;
  height: 100vh;
}

.left {
  flex: 2;
}

.right {
  flex: 1;
}

#mapB {
  width: 100%;
  height: 100%;
}

.bm-view {
  width: 100%;
  height: 100%;
}

.scroll-text {
  width: 400px;
  height: 150px;
  overflow: auto;
  border: 1px solid #ccc;
  padding: 10px;
  margin-top: 18px;
}
</style>
